package com.buildings.activity;

import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Matrix;
import android.graphics.Paint;
import android.graphics.drawable.BitmapDrawable;
import android.location.Criteria;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.provider.Settings;
import android.text.TextUtils;
import android.util.Log;
import android.view.MotionEvent;
import android.view.ScaleGestureDetector;
import android.view.View;
import android.widget.TextView;

import com.amap.api.location.AMapLocation;
import com.amap.api.location.AMapLocationClient;
import com.amap.api.location.AMapLocationClientOption;
import com.amap.api.location.AMapLocationListener;
import com.buildings.R;
import com.buildings.base.BaseActivity;
import com.buildings.bean.SimpleCoodinates;
import com.buildings.map.ArcGisUtil;
import com.buildings.map.TianDiMapUtils;
import com.buildings.util.DialogUtils;
import com.buildings.util.EvilTransform;
import com.buildings.util.GPSUtil;
import com.esri.arcgisruntime.geometry.AreaUnit;
import com.esri.arcgisruntime.geometry.AreaUnitId;
import com.esri.arcgisruntime.geometry.GeodeticCurveType;
import com.esri.arcgisruntime.geometry.GeometryEngine;
import com.esri.arcgisruntime.geometry.Point;
import com.esri.arcgisruntime.geometry.PointCollection;
import com.esri.arcgisruntime.geometry.Polygon;
import com.esri.arcgisruntime.geometry.PolygonBuilder;
import com.esri.arcgisruntime.geometry.Polyline;
import com.esri.arcgisruntime.geometry.SpatialReference;
import com.esri.arcgisruntime.geometry.SpatialReferences;
import com.esri.arcgisruntime.layers.WebTiledLayer;
import com.esri.arcgisruntime.mapping.ArcGISMap;
import com.esri.arcgisruntime.mapping.view.BackgroundGrid;
import com.esri.arcgisruntime.mapping.view.DefaultMapViewOnTouchListener;
import com.esri.arcgisruntime.mapping.view.Graphic;
import com.esri.arcgisruntime.mapping.view.GraphicsOverlay;
import com.esri.arcgisruntime.mapping.view.LocationDisplay;
import com.esri.arcgisruntime.mapping.view.MapView;
import com.esri.arcgisruntime.symbology.LineSymbol;
import com.esri.arcgisruntime.symbology.MarkerSymbol;
import com.esri.arcgisruntime.symbology.PictureMarkerSymbol;
import com.esri.arcgisruntime.symbology.SimpleFillSymbol;
import com.esri.arcgisruntime.symbology.SimpleLineSymbol;
import com.esri.arcgisruntime.symbology.SimpleMarkerSymbol;
import com.esri.arcgisruntime.symbology.SimpleRenderer;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import androidx.annotation.DrawableRes;
import androidx.annotation.Nullable;
import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

public class MapActivity extends BaseActivity implements AMapLocationListener {
    @BindView(R.id.gis_map)
    MapView mapView;
    @BindView(R.id.tv_title)
    TextView tvTitle;
    @BindView(R.id.tv_right_text)
    TextView tvightText;
    //声明AMapLocationClient类对象
    public AMapLocationClient mLocationClient = null;

    private WebTiledLayer vectorBaseMap;
    private WebTiledLayer vectorBaseMapAnno;
    private ArcGisUtil arcGisUtil;
    private ArcGISMap map;
    List<Point> list = new ArrayList<>();
    List<Point> list1 = new ArrayList<>();
    // 1 线 2面 3完成
    private int type = 1;
    private String result = "";

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_data_map);
        ButterKnife.bind(this);
        initMap();
        //initLocation();
        initAndroidLocation();
        initData();
    }

    public void initData(){
        if (getIntent().hasExtra("MapInfos")){
            result = getIntent().getStringExtra("MapInfos");
        }
        if (!TextUtils.isEmpty(result)){
            drawableMapPoint(result);
        }
    }

    public void drawableMapPoint(String data) {
        if (TextUtils.isEmpty(data)) {
            return;
        }
        if (!data.contains("type||")) {
            return;
        }
        String[] typeArr = data.split("type");
        for (int i = 0; i < typeArr.length; i++) {
            if (typeArr[i].startsWith("||line:")) {
                //线
                String pointArrData = typeArr[i].substring(7);
                String[] pointArr = pointArrData.split(";");
                if (pointArr.length == 0){
                    return;
                }
                showLine(pointArr);
            } else if (typeArr[i].startsWith("||polygon:")) {
                //面
                String pointArrData = typeArr[i].substring(10);
                String[] pointArr = pointArrData.split(";");
                if (pointArr.length == 0){
                    return;
                }
                showPolygon(pointArr);
            }
        }
    }

    private void showLine(String[] pointArr) {
        if (pointArr.length == 0){
            return;
        }
        List<Point> points = new ArrayList<>();
        for (int i = 0;i<pointArr.length;i++){
            String[] pointStr = pointArr[i].split(",");
            double lat = Double.parseDouble(pointStr[0]);
            double lon = Double.parseDouble(pointStr[1]);
            Point point = new Point(lat,lon,SpatialReferences.getWgs84());
            points.add(point);
        }
        drawArcgisLine(points);
    }

    private void showPolygon(String[] pointArr) {
        if (pointArr.length == 0){
            return;
        }
        List<Point> points = new ArrayList<>();
        for (int i = 0;i<pointArr.length;i++){
            String[] pointStr = pointArr[i].split(",");
            double lat = Double.parseDouble(pointStr[0]);
            double lon = Double.parseDouble(pointStr[1]);
            Point point = new Point(lat,lon);
            points.add(point);
        }
        drawArcGisFill(points);
    }

    private LocationManager locationManager;

    public void initAndroidLocation() {
        LocationDisplay locationDisplayManager = mapView.getLocationDisplay();//获取定位类
        locationDisplayManager.setShowLocation(true);
        locationDisplayManager.setShowLocation(true);
        locationDisplayManager.addLocationChangedListener(new LocationDisplay.LocationChangedListener() {
            @Override
            public void onLocationChanged(LocationDisplay.LocationChangedEvent locationChangedEvent) {
                locationPoint = locationChangedEvent.getLocation().getPosition();
                if (locationPoint == null){
                    return;
                }
                if (i == 1) {
                    moveMapCenter(locationPoint);
                    i++;
                }
            }
        });
        locationDisplayManager.startAsync();//开始定位
    }

    public void initMap() {
        tvTitle.setText("选择地图范围");
        tvightText.setText("完成");
        arcGisUtil = new ArcGisUtil(this, mapView);
        map = new ArcGISMap();

        vectorBaseMap = TianDiMapUtils.getTianDiMap(TianDiMapUtils.MapType.URL_CN_VECTORBASEMAP);
        vectorBaseMapAnno = TianDiMapUtils.getTianDiMap(TianDiMapUtils.MapType.URL_CN_VECTORBASEMAP_ANNOTATION);

        List<WebTiledLayer> vectorBaseMapLayerList = new ArrayList<>();
        vectorBaseMapLayerList.add(vectorBaseMap);
        vectorBaseMapLayerList.add(vectorBaseMapAnno);

        map.setMaxScale(TianDiMapUtils.getSCALES()[TianDiMapUtils.getSCALES().length - 1]);
        mapView.setMap(map);
        mapView.setAttributionTextVisible(false);
        mapView.setBackgroundGrid(new BackgroundGrid(Color.WHITE, Color.WHITE, 0, 2f));
        map.getOperationalLayers().addAll(vectorBaseMapLayerList);

        vectorBaseMap.loadAsync();
        vectorBaseMapAnno.loadAsync();

        mapView.setOnTouchListener(new DefaultMapViewOnTouchListener(this, mapView) {

            @Override
            public boolean onSingleTapConfirmed(MotionEvent e) {
                Point p = mapView.screenToLocation(new android.graphics.Point((int) e.getX(), (int) e.getY()));
                Point mapPoint = (Point) GeometryEngine.project(p, SpatialReference.create(4326));
                loadUnitMarkerData(p);

                list.add(mapPoint);
                if (type == 1) {
                    drawArcgisLine(list);
                } else {
                    if (list.size() >= 3) {
                        drawArcGisFill(list);
                        //  drawArcgisLine(list);
                    } else {

                    }
                }
                return true;
            }

            @Override
            public boolean onRotate(MotionEvent event, double rotationAngle) {
                return false;
            }
        });
    }

    public void initLocation() {
        //初始化定位
        mLocationClient = new AMapLocationClient(getApplicationContext());
        //初始化AMapLocationClientOption对象
        AMapLocationClientOption mLocationOption = new AMapLocationClientOption();
        //设置定位场景
        mLocationOption.setLocationPurpose(AMapLocationClientOption.AMapLocationPurpose.Sport);
        //设置定位模式为AMapLocationMode.Hight_Accuracy，高精度模式。
        mLocationOption.setLocationMode(AMapLocationClientOption.AMapLocationMode.Hight_Accuracy);
        //设置定位间隔,单位毫秒,默认为2000ms，最低1000ms。
        mLocationOption.setInterval(5000);
        //设置是否返回地址信息（默认返回地址信息）
        mLocationOption.setNeedAddress(true);
        //关闭缓存机制
        mLocationOption.setLocationCacheEnable(false);
        //设置定位回调监听
        mLocationClient.setLocationListener(this);
        //给定位客户端对象设置定位参数
        mLocationClient.setLocationOption(mLocationOption);
        //启动定位
        mLocationClient.startLocation();
    }

    private Point locationPoint;
    private int i = 1;

    @Override
    public void onLocationChanged(AMapLocation aMapLocation) {
        //gcj_02转wgs84
//        double[] arr = GPSUtil.gcj02_To_Gps84(aMapLocation.getLongitude(), aMapLocation.getLatitude());
//        Point point = new Point(aMapLocation.getLongitude(), aMapLocation.getLatitude(), SpatialReference.create(4326));
//        locationPoint = point;
//        loadMeMarkerData(point);
//        //移动
//        if (i == 1) {
//            moveMapCenter(locationPoint);
//            i++;
//        }
    }

    private void moveMapCenter(Point point) {
        mapView.setViewpointCenterAsync(point, TianDiMapUtils.getSCALES()[16]);
    }

    String layerIndex = "1";


    @OnClick({R.id.button, R.id.button1, R.id.iv_back, R.id.tv_right_text, R.id.iv_map_mylocation})
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.iv_back:
                finish();
                break;
            case R.id.iv_map_mylocation:
                if (null != locationPoint) {
                    moveMapCenter(locationPoint);
                }
                break;
            case R.id.button:
                //TODO 调用保存表单接口
                if (list.size() != 0) {
                    String line = "";
                    for (Point point : list) {
                        line = line + point.getX() + "," + point.getY() + ";";
                    }
                    if (type == 1) {
                        result += "type||line:" + line;
                    } else {
                        result += "type||polygon:" + line;
                    }
                }
                list.clear();
                type = 1;
                break;
            case R.id.button1:
                //TODO 调用保存表单接口
                if (list.size() != 0) {
                    String polygon = "";
                    for (Point point : list) {
                        polygon = polygon + point.getX() + "," + point.getY() + ";";
                    }
                    if (type == 1) {
                        result += "type||line:" + polygon;
                    } else {
                        result += "type||polygon:" + polygon;
                    }
                }
                list.clear();
                type = 2;
                break;
            case R.id.tv_right_text:
                String polygon1 = "";
                for (Point point : list) {
                    polygon1 = polygon1 + point.getX() + "," + point.getY() + ";";
                }
                if (type == 1) {
                    result += "type||line:" + polygon1;
                } else {
                    result += "type||polygon:" + polygon1;
                }
                list.clear();
                //TODO 调用保存表单接口
                Intent i = new Intent();
                i.putExtra("result", result);
                setResult(3, i);
                finish();
                break;
        }
    }

    /**
     * map画线
     */
    private void drawArcgisLine(List<Point> points) {
        PointCollection pointCollection = new PointCollection(points);
        Polyline mPolyline = new Polyline(pointCollection);//点画线，mPoints为坐标集合
        GraphicsOverlay graphicsOverlayPump = new GraphicsOverlay();
        mapView.getGraphicsOverlays().add(graphicsOverlayPump);
        SimpleLineSymbol lineSym =
                new SimpleLineSymbol(SimpleLineSymbol.Style.SOLID, getResources().getColor(R.color.task_status_unfinished), 5);
        Graphic graphicTrail = new Graphic(mPolyline, lineSym);
        graphicsOverlayPump.getGraphics().add(graphicTrail);
    }

    private List<Graphic> graphicListPump;

    public static HashMap<Class, GraphicsOverlay> drawLayerMap = new HashMap<>();

    /**
     * 加载地图marker元素数据
     */
    private void loadUnitMarkerData(Point point) {
        MarkerSymbol mMarkerSymbol = new SimpleMarkerSymbol(
                SimpleMarkerSymbol.Style.CIRCLE,
                Color.BLUE, 10
        );
        //添加点
        GraphicsOverlay graphicsOverlayPump = new GraphicsOverlay();
        mapView.getGraphicsOverlays().add(graphicsOverlayPump);
        graphicsOverlayPump.getGraphics().add(new Graphic(point, new HashMap<String, Object>(), mMarkerSymbol));
    }

    private void drawArcGisFill(List<Point> points) {
        PolygonBuilder polygonGeometry = new PolygonBuilder(SpatialReferences.getWgs84());
        for (Point pd : points) {
            polygonGeometry.addPoint(pd.getX(), pd.getY());
        }
        // solid yellow polygon symbol
        SimpleFillSymbol polygonSymbol =
                new SimpleFillSymbol(SimpleFillSymbol.Style.SOLID, getResources().getColor(R.color.task_status_unfinished), null);
        // create graphic for polygon
        Graphic polygonGraphic = new Graphic(polygonGeometry.toGeometry());
        // create graphic overlay for polygon
        GraphicsOverlay polygonGraphicOverlay = new GraphicsOverlay();
        // create simple renderer
        SimpleRenderer polygonRenderer = new SimpleRenderer(polygonSymbol);
        // add graphic to overlay
        polygonGraphicOverlay.setRenderer(polygonRenderer);
        // add graphic to overlay
        polygonGraphicOverlay.getGraphics().add(polygonGraphic);
        // add graphics overlay to MapView
        mapView.getGraphicsOverlays().add(polygonGraphicOverlay);
    }

    /**
     * 加载地图marker元素数据
     */
    private void loadMeMarkerData(Point point) {
        //添加点
        GraphicsOverlay graphicsOverlayPump = arcGisUtil.addGraphicsOverlay();
        if (i != 1) {
            graphicsOverlayPump.getGraphics().remove(0);
        }
        GraphicsOverlay graphicsOverlayWaterStation = arcGisUtil.addGraphicsOverlay();
        Bitmap bitmap = changeSize(R.drawable.arcgisruntime_location_display_default_symbol);
        PictureMarkerSymbol iconPump = new PictureMarkerSymbol(new BitmapDrawable(bitmap));
        graphicsOverlayPump.getGraphics().add(new Graphic(point, new HashMap<>(), iconPump));
    }

    /**
     * 图片资源大小不契合，需要缩放
     *
     * @param drawable 图片资源
     * @return 新的图片资源
     */
    private Bitmap changeSize(@DrawableRes int drawable) {
        Bitmap originalBitmap = BitmapFactory.decodeResource(getResources(), drawable);
        int originalWidth = originalBitmap.getWidth();
        int originalHeight = originalBitmap.getHeight();
        int newWidth = 70;
        int newHeight = 70; // 自定义 高度 暂时没用

        float scale = ((float) newHeight) / originalHeight;
        Matrix matrix = new Matrix();
        matrix.postScale(scale, scale);
        return Bitmap.createBitmap(originalBitmap, 0, 0,
                originalWidth, originalHeight, matrix, true);//你的 ImageView
    }
}
